package com.taoym.voucher.job.handler;

import com.taoym.voucher.common.response.ResponseStatusCode;
import com.taoym.voucher.common.utils.ExceptionCore;
import com.taoym.voucher.common.utils.JwtTokenUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @coder taoym
 * @datetime 2021/7/1 22:24
 * @desc 请求拦截器
 */
@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String authorization = request.getHeader("Authorization");
        if (!ObjectUtils.isEmpty(authorization) && authorization.startsWith("Bearer")) {
            String token = authorization.substring("Bearer".length()).trim();
            JwtTokenUtils.validateTokenIsExpired(token, false);
            return true;
        } else {
            throw new ExceptionCore(ResponseStatusCode.ILLEGAL_ACCESS);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
